<template>
  <div>
    <a-modal v-model:visible="visible" :width="900" title="新增船运合同" @cancel="cacelModel" :bodyStyle="bodyStyle"  @ok="handleOk">
      <a-form :model="formState" labelAlign="left" ref="shopAddForm" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="16">
        <a-col :span="9" :style="{paddingBottom: '10px'}">
          <div class="custom-drag">
            <div>
          <a-form-item name="dragger" no-style>
            <a-upload-dragger v-model:fileList="fileList"
                              :max-count="1"
                              :beforeUpload="beforeUpload"
                              @change="postFile"
                              :customRequest="customRequest"
                              :style="{border: 0}"
                              @remove="fileRemove"
                              name="file"
                              accept=".pdf">
              <div class="dragger-img">
                <img src="@/assets/images/ResourceContract/file.png" alt="">
              </div>
              <p class="ant-upload-text" :style="{color: '#2C3749'}">将文件拖到此处，或 <span :style="{color: '#0062AD'}">点击上传</span> </p>
              <p class="ant-upload-hint" :style="{color: '#6B7A8B', fontSize: '14px'}" >只支持pdf格式</p>
            </a-upload-dragger>
<!--            <a-upload-dragger v-model:fileList="fileList"-->
<!--                              :max-count="1"-->
<!--                              :action="action"-->
<!--                              :data="{contractType: 'con_shipping'}"-->
<!--                              :beforeUpload="beforeUpload"-->
<!--                              @change="postFile"-->
<!--                              :style="{border: 0}"-->
<!--                              name="file"-->
<!--                              accept=".pdf"-->
<!--            >-->
<!--              <div class="dragger-img">-->
<!--                <img src="@/assets/images/ResourceContract/file.png" alt="">-->
<!--              </div>-->
<!--              <p class="ant-upload-text" :style="{color: '#2C3749'}">将文件拖到此处，或 <span :style="{color: '#0062AD'}">点击上传</span> </p>-->
<!--              <p class="ant-upload-hint" :style="{color: '#6B7A8B', fontSize: '14px'}" >只支持pdf格式</p>-->
<!--            </a-upload-dragger>-->
          </a-form-item>
            </div>
          </div>
        </a-col>
        <a-col :span="15">
          <a-form-item label="文件类型" name="fileType" :rules="[{ required: true, message: '请选择文件类型' }]">
            <a-radio-group v-model:value="formState.fileType">
              <a-radio value="1">term sheet</a-radio>
              <a-radio value="2">合同文件</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-spin :spinning="spinning" tip="文件正在识别中...">
          <div class="form-item-border">
            <a-form-item label="合同类型" name="contractType" :rules="[{ required: true, message: '请选择合同类型' }]">
              <a-select :bordered="false" v-model:value="formState.contractType" placeholder="请选择合同类型" :options="contractTypeAreas" />
            </a-form-item>
          </div>
            <div class="form-item-border">
              <a-form-item label="船舶名称" name="shipName" :rules="[{ required: true, message: '请输入船舶名称' }]">
                <a-input :bordered="false" v-model:value="formState.shipName" placeholder="请输入船舶名称"/>
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item label="舱容" name="shipName" :rules="[{ required: true, message: '请输入舱容' }]">
                <a-input-number :bordered="false" :style="{width: '100%'}" v-model:value="formState.cabinCapacity" placeholder="请输入舱容">
                  <template #addonAfter>
                    <div class="numAfter">
                      m³
                    </div>
                  </template>
                </a-input-number>
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item label="IMO" name="imo" :rules="[{ required: true, message: '请输入IMO' }]">
                <a-input :bordered="false" v-model:value="formState.imo" placeholder="请输入IMO"/>
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item label="船东"  name="shipowner" :rules="[{ required: true, message: '请输入船东' }]">
                <a-input :bordered="false" v-model:value="formState.shipowner" placeholder="请输入船东"/>
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item label="租家" name="tenant" :rules="[{ required: true, message: '请输入租家' }]">
                <a-input :bordered="false" v-model:value="formState.tenant" placeholder="请输入租家"/>
              </a-form-item>
            </div>
          <div class="form-item-border">
            <a-form-item label="贸易主体" name="tradeBody" :rules="[{ required: true, message: '请选择贸易主体' }]">
              <a-select :bordered="false" v-model:value="formState.tradeBody" placeholder="请选择贸易主体" :options="tradeareas" />
            </a-form-item>
          </div>
            <div class="form-item-flex">
              <div class="form-item-border">
                <a-form-item label="租期" name="leaseTerm" :rules="[{ required: true, message: '请输入' }]">
                  <a-input-number :bordered="false" v-model:value="formState.leaseTerm" :style="{width: '100%'}" placeholder="请输入租期"  :min="1" />
                </a-form-item>
              </div>
              <div class="form-item-border" :style="{padding: 0}">
                <a-form-item name="Capacity1" :rules="[{ required: true, message: '请选择' }]">
                  <a-input :style="{width: '30px', padding: 0, textAlign: 'center', fontSize: '20px'}"  disabled  :bordered="false" v-model:value="formState.Capacity1"></a-input>
                </a-form-item>
              </div>
              <div class="form-item-border">
                <a-form-item name="leaseTermValueUp" :rules="[{ required: true, message: '请输入' }]">
                  <a-input-number :style="{width: '100px'}"
                                  placeholder="请输入"
                                  :bordered="false"
                                  addon-after="天"
                                  v-model:value="formState.leaseTermValueUp"
                  />
                </a-form-item>
              </div>
              <div class="form-item-border" :style="{padding: 0}">
                <a-form-item name="Capacity3" :rules="[{ required: true, message: '请选择' }]">
                  <a-input :style="{width: '30px', padding: 0, textAlign: 'center', fontSize: '20px'}"  disabled  :bordered="false" v-model:value="formState.Capacity3"></a-input>
                </a-form-item>
              </div>
              <div class="form-item-border">
                <a-form-item name="leaseTermValueUpDown" :rules="[{ required: true, message: '请输入' }]">
                  <a-input-number :style="{width: '100px'}"
                                  placeholder="请输入"
                                  :bordered="false"
                                  addon-after="天"
                                  v-model:value="formState.leaseTermValueUpDown"
                  />
                </a-form-item>
              </div>
            </div>
          <div class="form-item-border">
            <a-form-item label="交船日期" name="deliveryDates" :rules="[{required: true, message: '请选择交船日期' }]">
              <a-range-picker :locale="locale" :bordered="false" :style="{width: '100%'}" v-model:value="formState['deliveryDates']"
                              :show-time="{ format: 'HH:mm' }"
                              placeholder="请选择交船日期"
                             value-format="YYYY-MM-DD HH:mm" />
            </a-form-item>
          </div>
          <div class="form-item-border">
            <a-form-item label="租金" name="rent" :rules="[{ required: true, message: '请输入租金' }]">
              <a-input-number :bordered="false"  v-model:value="formState.rent" :style="{width: '100%'}" placeholder="请输入租金"  :min="1" >
                <template #addonAfter>
                  <a-select  style="width: 100px" v-model:value="formState.currency">
                    <a-select-option :value="1">美元</a-select-option>
                    <a-select-option :value="2">人民币</a-select-option>
                    <a-select-option :value="3">欧元</a-select-option>
                  </a-select>
                </template>
              </a-input-number>
            </a-form-item>
          </div>
            <div class="form-item-border">
              <a-form-item label="合同签订日期" name="signingDate" :rules="[{ type: 'string', required: false, message: '请选择合同签订日期' }]">
                <a-date-picker :locale="locale" :bordered="false" :style="{width: '100%'}" v-model:value="formState['signingDate']"  value-format="YYYY-MM-DD" />
              </a-form-item>
            </div>
          </a-spin>
        </a-col>
      </a-row>
      </a-form>
      <template #footer>
        <div class="from-btn-right">
          <a-button key="back" class="border-btn" @click="cacelModel">取消</a-button>
          <a-button key="submit" @click="handleOk" :loading="confirmLoading" class="search-btn1">保存</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import {getCurrentInstance, reactive, ref, defineEmits, onMounted} from "vue";
import {message} from "ant-design-vue";
const { proxy  } = getCurrentInstance()
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import 'dayjs/locale/zh-cn';
import {BASE_URL} from "@/config/proxyIp";
import axios from "axios";
const visible = ref(false);
const isSubmit = ref(false)
const emit = defineEmits(['saveMemForm'])
const fileList = ref([])
const action = ref(`${BASE_URL}/con/common/uploadContractWithAnalysis`)
const bodyStyle = ref({})
// 合同类型
const contractTypeAreas = ref([
  {
    label: '租入长期船',
    value: 1
  },
  {
    label: '租入短期船',
    value: 2
  },
  {
    label: '船舶租出',
    value: 3
  },
  {
    label: '内部转租',
    value: 4
  }
])
// 贸易主体
const tradeareas = ref([
  {
    label: '国贸',
    value: 1
  },
  {
    label: '新贸',
    value: 2
  },
])
const areas2 = ref([
  {
    label: '+',
    value: 1
  },
  {
    label: '-',
    value: 2
  },
  {
    label: '±',
    value: 3
  }
])
const labelCol = ref(
    {
      style: {
        width: '100px'
      },
    },
)

const wrapperCol = ref({
  span: 20
})
const formState = reactive({
  contractNumber: '', //合同编号
  contractName: '', //合同名称
  contractType: undefined, // 合同类型
  tradeType: '', // 贸易主体
  signingDate: '', // 签订日期
  imo: '', // IMO
  shipName: '', // 船舶名称
  shipowner: '', // 船东
  tenant: '', // 租家
  leaseTerm: '', // 租期
  startingDateOfLeaseBegin: '', // 起租日期-开始
  startingDateOfLeaseEnd: '', // 起租日期-结束
  startingDateOfLease: '', // 起租日期
  rent: '', // 租金(每天)
  deliveryDateBegin: '', // 交船日期-开始
  deliveryDateEnd: '', // 交船日期-结束
  deliveryDate: '', // 交船日期
  deliveryDates: '', // 交船日期
  placeOfDeliveryOfShip: '', // 交船地点
  redeliveryDateBegin: '', // 还船日期-开始
  redeliveryDateEnd: '', // 还船日期-结束
  redeliveryDate: '', // 还船日期
  placeOfRedeliveryOfShip: '', //还船地点
  shipSpeed: '', // 船速(Knots)
  shipSpeedForRedeliveryFee: '', // 船速（用作计算交还船费）
  deliveryStatus: '', // 交船状态
  deliveryStatusDetail: '', // 交船状态自定义内容
  redeliveryStatus: '', // 还船状态(数值，单位立方米)
  deliveryFuelQuantity: '', // 交船燃油量
  refundFuelQuantity: '', // 还船燃油量
  deliveryLngVolume: '', // 交船LNG量
  lngQuantityReturnedToTheShip: '', // 还船LNG量
  deliveryNotice: '', // 交船通知
  redeliveryNotice: '', // 还船通知
  cabinCapacity: '', // 舱容（单位立方米）
  deliveryFee: '', // 交船费
  redeliveryFee: '', // 还船费
  declareReserveAmount: '', // 宣布留底量(单位天)
  lngPriceDelivery: '', // LNG价格（交船）
  lngPriceRedelivery: '', // LNG价格（还船）
  fuelUsagePrinciples: '', // 燃油使用原则(FIFO、LILO)
  evaporationRate: '', // 船保证的满载蒸发率
  oilConsumptionEnsure: '', // 油耗保证（tons/day）
  currency: 1, // 币种
  contractStatus: '', // 合同状态
  createDate: '', // 容创建时间
  createBy: '', // 创建人
  filePath: '',
  fileType: '',
  leaseTermUnit: '', // 租期类型
  leaseTermValue: '', // 误差值
  leaseTermValueUp: '',
  leaseTermValueUpDown: '',
  Capacity1: '+',
  Capacity3: '-'
})
const shopAddForm = ref()
let cancelSourceList = ref([])
const spinning = ref(false)
const showModal = () => {
  visible.value = true
  fileList.value = []
  console.log('formAdd', shopAddForm.value)
};
const cacelModel = () =>{
  visible.value = false
  isSubmit.value = false
  fileList.value = []
  shopAddForm.value.resetFields()
  cancelSourceList.value[0].cancel()
  spinning.value = false
  isSubmit.value = true
  confirmLoading.value = false
}
const confirmLoading = ref(false)
const handleOk = () => {
  if(formState.filePath) {
    shopAddForm.value.validateFields().then(() => {
      console.log('上传的formData', formState);
      formState.deliveryDateBegin = formState.deliveryDates[0]
      formState.deliveryDateEnd = formState.deliveryDates[1]
      confirmLoading.value = true
      proxy.$api.postAddShipping(formState).then(res => {
        if (res.resultCode === 0) {
          visible.value = false;
          isSubmit.value = true
          confirmLoading.value = false
          emit('saveMemForm', isSubmit.value)
          message.success('新增船运合同成功')
          shopAddForm.value.resetFields()
        }
      })
    }).catch(err => {
      console.log('请输入', err)
    })
  } else {
    message.error('请上传船运合同')
  }
}
const postFile = (info) => {
  console.log('上传文件1', info)
  const status = info.file.status
  if (status === 'done') {
    formState.filePath = info.file.response.resultObject.path
    console.log('上传文件返回的参数', info.file.response)
    const contractData = info.file.response.resultObject.contractData
    let contractKey = Object.keys(contractData)
    if (contractKey.length === 0) {
      message.error('识别失败，请手动输入')
    } else {
      Object.assign(formState, contractData)
    }
    spinning.value = false
    console.log('解析出来的参数', formState)
  } else if (status === 'error') {
    spinning.value = false
    message.error(`${info.file.name} 文件上传失败`);
  }
}
const beforeUpload = (file) => {
  console.log('上传文件2', file)
  let houzui = file.name.substring(file.name.lastIndexOf('.'), file.name.length).toLowerCase()
  let res = ['.pdf'].includes(houzui)
  if (!res) {
    fileList.value = []
    message.error('请上传 PDF 文件')
  }
  spinning.value = true
  return res
}
const customRequest = (options) => {
  let { file, onSuccess, onError } = options
  const CancelToken = axios.CancelToken
  const source = CancelToken.source()
  const formData = new FormData()
  formData.append('file', file )
  formData.append('contractType', 'con_shipping' )
  cancelSourceList.value.push(source)
  //importExcelFinalUrl是你的接口url
  axios.post(action.value, formData, {
    cancelToken: source.token
  }).then((res) => {
    file.status = 'done'
    //这里onSuccess的第一个参数是接口响应结果，会传到change事件中去
    onSuccess(res.data, file)
  }).catch((res) => {
    file.status = 'error'
    onError(res.data, file)
  })
}
const fileRemove = () => {
  console.log('点击移除了?',  cancelSourceList.value)
  cancelSourceList.value[0].cancel()
  spinning.value = false
  shopAddForm.value.resetFields()
}
onMounted(() => {
  console.log('window.screen.width', window.screen.width)
  if (window.screen.width < 1920) {
    const bodyObj = {
      height: '400px',
      overflow: 'auto'
    }
    bodyStyle.value = bodyObj
  } else {
    bodyStyle.value = {}
  }
})
// eslint-disable-next-line no-undef
defineExpose({
  showModal,
  handleOk
})
</script>

<style lang="scss" scoped>
.form-item-flex {
  display: flex;
  justify-content: space-between;
  .form-item-border {
    margin-right: 4px;
  }
}
.from-btn-right {
  height: 62px;
  line-height: 62px;
  background: #ffffff;
 // box-shadow: 0px -4px 9px 0px rgba(0,0,0,0.09);
}
.dragger-img {
  margin-top: 40%;
  img {
    width: 114px;
    height: 110px;
  }
}
.custom-drag {
  width: 100%;
  height: 100%;
  border: 1px solid #DCDEE0;
  &:hover {
    border-color: #40a9ff;
  }
  &:active {
    border-color: #40a9ff;
  }
}
</style>
